package com.breakfast.fun.ui.home.product;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.breakfast.fun.Constant;
import com.breakfast.fun.R;
import com.breakfast.fun.base.BaseActivity;
import com.breakfast.fun.base.BaseModel;
import com.breakfast.fun.base.BasePresenter;
import com.breakfast.fun.dao.DaoMaster;
import com.breakfast.fun.dao.ProductCart;
import com.breakfast.fun.dao.ProductCartDao;
import com.breakfast.fun.data.entity.home.Product;
import com.breakfast.fun.data.entity.home.Products;
import com.breakfast.fun.event.CartEvent;
import com.breakfast.fun.ui.home.gallery.ProductCommentActivity;
import com.breakfast.fun.ui.user.cart.UserCartActivity;
import com.breakfast.fun.util.Api;
import com.breakfast.fun.util.T;
import com.breakfast.fun.view.widget.TitleBarView;
import com.bumptech.glide.Glide;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.greendao.query.Query;
import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

import butterknife.Bind;

public class SpecialDetailActivity extends BaseActivity<BasePresenter, BaseModel> {

    @Bind(R.id.iv_special_detail)
    ImageView mIvSpecialDetail;
    @Bind(R.id.tv_special_detail_name)
    TextView mTvSpecialDetailName;
    @Bind(R.id.tv_special_detail_price)
    TextView mTvSpecialDetailPrice;
    @Bind(R.id.tv_special_detail_del)
    TextView mTvSpecialDetailDel;
    @Bind(R.id.tv_special_detail_num)
    TextView mTvSpecialDetailNum;
    @Bind(R.id.tv_special_detail_add)
    TextView mTvSpecialDetailAdd;
    @Bind(R.id.ll_special_detail)
    LinearLayout mLlSpecialDetail;
    @Bind(R.id.rl_special_detail)
    RelativeLayout mRlSpecialDetail;
    @Bind(R.id.wv_special_detail)
    WebView mWvSpecialDetail;
    @Bind(R.id.rl_special_comment)
    RelativeLayout mRlSpecialComment;
    @Bind(R.id.tbv_special_detail)
    TitleBarView mTbvSpecialDetail;
    @Bind(R.id.tv_special_detail_buy)
    TextView mTvSpecialDetailBuy;
    @Bind(R.id.iv_special_detail_arrow)
    ImageView mIvSpecialDetailArrow;

    private Products mProducts;
    private Product product;

    private static ProductCartDao productCartDao;
    private static QueryBuilder qb;

    private int totalNum = 0;
    private double totalPrice = 0;
    private CartEvent event = new CartEvent();

    private Boolean isExpand = false;

    @Override
    public int getLayoutId() {
        return R.layout.activity_special_detail;
    }

    @Override
    public void initView() {

        productCartDao = DaoMaster.newDevSession(context, "zaofan.db").getProductCartDao();
        qb = productCartDao.queryBuilder();
        qb.LOG_SQL = true;
        qb.LOG_VALUES = true;
        List<ProductCart> productCarts = productCartDao.loadAll();
        for (int i = 0; i < productCarts.size(); i++) {
            totalPrice += productCarts.get(i).getTotalPrice();
            totalNum += productCarts.get(i).getNum();
        }
        event.setTotalPrice(totalPrice);
        event.setTotalNum(totalNum);
        EventBus.getDefault().post(event);

        mTbvSpecialDetail.setBack(this);
        mTbvSpecialDetail.setTitleNoRight("商品详情");

        mProducts = (Products) getIntent().getSerializableExtra("products");
        product = mProducts.getProduct();
        imageUtil.loadUrlImage(product.getImage(), mIvSpecialDetail);
        Glide.with(context)
                .load(product.getImage())
                .placeholder(R.drawable.bg_cache_banner)
                .error(R.drawable.bg_cache_banner)
                .crossFade()
                .into(mIvSpecialDetail);

        mTvSpecialDetailName.setText(product.getDes());
        mTvSpecialDetailPrice.setText("￥" + String.format("%.2f", product.getPrice()));

        List<ProductCart> list = getProductList(product.getCategoryId(), product.getId(), SpecialProductActivity.chooseDate);
        if (list.size() > 0) {
            mTvSpecialDetailNum.setText(list.get(0).getNum() + "");
        }

        if (TextUtils.isEmpty(product.getSdes())) {
            mWvSpecialDetail.loadDataWithBaseURL(Api.BASE_URL, "暂无", "text/html", "UTF-8", null);
        } else {
            mWvSpecialDetail.loadDataWithBaseURL(Api.BASE_URL, Constant.html1 + product.getSdes() + Constant.html2, "text/html", "UTF-8", null);
        }

        mTvSpecialDetailAdd.setOnClickListener(v -> {
            ProductCart productCart = new ProductCart(null, product.getCategoryId(), product.getId(), SpecialProductActivity.chooseDate);

            List<ProductCart> productCartList = getProductList(productCart.getCategoryId(), productCart.getProductId(), SpecialProductActivity.chooseDate);

            if (productCartList.size() == 0) {
                productCart.setNum(1);
                productCart.setImage(product.getImage());
                productCart.setProductId(product.getId());
                productCart.setName(product.getName());
                productCart.setProductId(product.getId());
                productCart.setPrice(product.getPrice());
                productCart.setProductClassId(product.getProductClassId());
                productCart.setTotalPrice(product.getPrice());
                productCartDao.insert(productCart);
                mTvSpecialDetailNum.setText("1");
            } else {
                productCartList.get(0).setNum(productCartList.get(0).getNum() + 1);
                productCartList.get(0).setTotalPrice(productCartList.get(0).getPrice() * productCartList.get(0).getNum());
                productCartDao.update(productCartList.get(0));
                mTvSpecialDetailNum.setText(productCartList.get(0).getNum() + "");
            }
            totalNum += 1;
            totalPrice += product.getPrice();
            event.setTotalNum(totalNum);
            event.setTotalPrice(totalPrice);
            EventBus.getDefault().post(event);
        });

        mTvSpecialDetailDel.setOnClickListener(v -> {
            if (mTvSpecialDetailNum.getText().equals("0")) {
                return;
            }

            List<ProductCart> productCartList = getProductList(product.getCategoryId(), product.getId(), SpecialProductActivity.chooseDate);
            productCartList.get(0).setNum(productCartList.get(0).getNum() - 1);
            productCartDao.update(productCartList.get(0));
            mTvSpecialDetailNum.setText(productCartList.get(0).getNum() + "");
            if (mTvSpecialDetailNum.getText().equals("0")) {
                productCartDao.delete(productCartList.get(0));
            }
            totalNum -= 1;
            totalPrice -= product.getPrice();
            event.setTotalNum(totalNum);
            event.setTotalPrice(totalPrice);
            EventBus.getDefault().post(event);
        });

        mRlSpecialComment.setOnClickListener(v -> {
            Intent intent = new Intent(context, ProductCommentActivity.class);
            intent.putExtra("productId", product.getId() + "");
            startActivity(intent);
        });

        mTvSpecialDetailBuy.setOnClickListener(v -> {
            productCartDao = DaoMaster.newDevSession(context, "zaofan.db").getProductCartDao();
            if ((productCartDao.loadAll() == null ||
                    productCartDao.loadAll().size() == 0)) {
                T.show("购物车为空,请添加商品");
                return;
            }
            Intent intent = new Intent(context, UserCartActivity.class);
            startActivity(intent);
        });

        mRlSpecialDetail.setOnClickListener(v -> {
            if (!isExpand) {
                mWvSpecialDetail.setVisibility(View.VISIBLE);
                mIvSpecialDetailArrow.setImageResource(R.drawable.ic_arrow_up_gray);
            } else {
                mWvSpecialDetail.setVisibility(View.GONE);
                mIvSpecialDetailArrow.setImageResource(R.drawable.ic_arrow_down_gray);
            }
            isExpand = !isExpand;
        });
    }

    public List<ProductCart> getProductList(int categoryId, int productId, String chooseDate) {
        qb = productCartDao.queryBuilder();
        ProductCart productCart = new ProductCart(null, categoryId, productId, chooseDate);
        Query query = qb.where(
                ProductCartDao.Properties.Date.eq(productCart.getDate()), ProductCartDao.Properties.ProductId.eq(productCart.getProductId()))
                .build();
        return query.list();
    }


}
